import { Dispatch } from 'redux'
import { setEnviron, request } from 'ad-ui-request'
import { snakeCase, isFunction } from 'ad-ui-utils'
import { api_base, api_user, api_order } from 'helper/interface'

// 设置接口请求
require('ad-ui-api')(request)

// request处理后的返回格式
export interface IHandleReturn {
  action: string
  code: string
  message: string
  response?: any
  error?: any
  status: number
  type?: string
}

interface IFunctionObject {
  [propName: string]: Function
}

setEnviron(__GATEWAY__, __ACTIVE_REDUCEDR_TOOLS__, __EP_PASSPORT_URL__, __COOKIE_DOMAIN__)

const wrap = (dispatch: Dispatch) => {
  window.Api = {
    base: wrapApiMethod(api_base, dispatch),
    user: wrapApiMethod(api_user, dispatch),
    order: wrapApiMethod(api_order, dispatch),
  }
}

const wrapApiMethod = (Raw: IFunctionObject, dispatch: Dispatch) => {

  const keys: string[] = Object.keys(Raw)
  const api = {}

  keys && keys.forEach((name: string): any => {
    const func = Raw[name]
    if (!func || !isFunction(func)) return null
    const snakeType = snakeCase(name)
    const TYPE = snakeType.toUpperCase()
    const LOADING = `${TYPE}_LOADING`
    const SUCCESS = `${TYPE}_SUCCESS`
    const FAILED = `${TYPE}_FAILED`

    const action = (params = {}) => {
      dispatch({ type: LOADING })

      return func(params).then(
        (response: IHandleReturn) => dispatch({ type: SUCCESS, response: response.response }),
        (error: Error) => dispatch({ type: FAILED, error })
      )
    }
    action.displayName = name
    action.promise = func

    api[LOADING] = LOADING
    api[SUCCESS] = SUCCESS
    api[FAILED] = FAILED
    api[name] = action
  })

  return api
}

export default wrap
